#!/usr/bin/env python
#-*-coding:utf-8-*-
from urllib import request,parse
from http import cookiejar
import json
import os
import re
from time import sleep

def get_title(s):
    url=s;
    rep=request.urlopen(s).read();
    read=rep.decode("utf-8");
    title=re.findall("bkey=.*?\"([0-9]+).*?sid=\"([0-9]+)\" ret=\"(.+?)\"",read);
#    print(title)
    name=re.findall("class='search-back'></a>(.+?)</div>",read);
    if(len(name)<=0) :
        name=re.findall("<title>(.+?)</title>",read);
#    print(name)
    return  title,name;
def downloand(html,name,title):
    print('正在加载..'+title,end='')
    path=name+"/"+title;
    pat=os.path.exists(path);
    if(not pat) :
        os.makedirs(path)
    i=1;
    for url in html:
        while True:
            try:
                png = request.urlopen(url=url, timeout=2).read();
#                print(i, url)
                with open(path + "/" + str(i), 'wb') as f:
                    f.write(png);
                    i = i + 1;
                    print('.',end='')
                    break
            except:
                i=i-1;
                sleep(0.5)

    print('       100')

def get_png(list,name):
    for page,sid,namee in list:
        url='http://www.zn678.cn/ht/app/index.php?i=1&c=entry&tid=317&do=read&m=iweite_xiaoshuo&bkey='+page+'&sid='+sid;
#        print(url)
        while True:
            try:
                page = request.urlopen(url=url,timeout=1).read().decode("utf-8");
                break
            except:
                pass
        html=re.findall('(http.+?(?:jpg|png|gif))',page);
        namee=namee.replace(' ','_');
        namee=namee.replace('\\','_');
        namee=namee.replace('/','_');
#        print(html,name,namee);
        downloand(html,name,namee);

def seach(string):
    url='http://www.zn678.cn/ht/app/index.php?i=1&c=entry&do=search&m=iweite_xiaoshuo';
    date=parse.urlencode({'query':string}).encode('utf-8');
    res=request.Request(url=url,data=date)
    while True:
        try:
            html = request.urlopen(res,timeout=2).read().decode('utf-8');
            break
        except:
            pass
    list_name=re.findall('result-title">(.+?)<',html)
    list_author=re.findall('<strong>(.+?)<',html);
    list_make=re.findall('出版社：.(.*?)<',html);
    list_id=re.findall('c=entry&id=([0-9]+)?',html)
#    print(list_name)
#    print(list_author)
#    print(list_make)
#    print(list_id)
#    return list_name,list_author,list_make,list_id
    i=0;
    print(len(list_name),len(list_author),len(list_make),len(list_id))
    for name in list_name:
        print(i,name, 'NULL'if (i>=len(list_author)) else list_author[i],'NULL' if(i>=len(list_make)) else list_make[i]);
        i+=1
    print(i,'退出 ')
    while True:
        print('请选择',end=' :')
        v=int(input())
        if(v==i) :
            return
        if(v>i or v<0):
            print('错误!!')
            continue
        man('http://www.zn678.cn/ht/app/index.php?i=1&c=entry&tid='+list_id[v]+'&do=mulu&m=iweite_xiaoshuo')
def man(url):
    print('加载中.....请耐心等待')
    if ('mulu' not in url):
        url = url.replace('show', 'mulu')
    if ('tid' not in url):
        url = url.replace('id', 'tid')
    s, nam = get_title(url)
    name = nam[0].replace(' ', '_');
    name = nam[0].replace('\\', '_');
    name = nam[0].replace('/', '_');
    get_png(list=s, name=name)


if __name__=='__main__':

    while True:
       print('\n1 输入链接 \n2 查询关键\n3退出');
       v= int(input());
       if(v==1):
           print('请输入链接',end=' :')
           man(input());
       elif v==3:
           break
       else:
           print('输入查询 ',end=' :')
           seach(input());
